using System;
using System.Collections.Generic;
using UnityEngine;

public class ConsoleToScreen : MonoBehaviour
{
    /// <summary>
    /// 最大行数
    /// </summary>
    const int maxLines = 50;

    /// <summary>
    /// 每行的最大长度
    /// </summary>
    const int maxLinesLength = 120;

    /// <summary>
    /// 存储完整日志的字符串
    /// </summary>
    private string _logStr = "";

    /// <summary>
    /// 存储按照最大行长度分割后的日志行
    /// </summary>
    private readonly List<string> _lines = new List<string>();

    /// <summary>
    /// 字体大小
    /// </summary>
    public int fontSize = 15;

    private void OnEnable()
    {
        Application.logMessageReceived += Log;
    }

    private void OnDisable()
    {
        Application.logMessageReceived -= Log;
    }


    private void Log(string logString, string stackTrace, LogType type)
    {
        foreach (string line in logString.Split('\n'))
        {
            if (line.Length <= maxLinesLength)
            {
                _lines.Add(line);
                continue;
            }

            var lineCount = line.Length / maxLinesLength + 1;
            for (int i = 0; i < lineCount; i++)
            {
                if ((i + 1) * maxLinesLength <= line.Length)
                {
                    _lines.Add(line.Substring(i * maxLinesLength, maxLinesLength));
                }
                else
                {
                    _lines.Add(line.Substring(i * maxLinesLength, line.Length - i * maxLinesLength));
                }
            }
        }

        if (_lines.Count > maxLines)
        {
            _lines.RemoveRange(0, _lines.Count - maxLines);
        }

        _logStr = string.Join("\n", _lines);
    }

    private void OnGUI()
    {
        // GUI.matrix将屏幕坐标转换为指定比例的屏幕尺寸
        GUI.matrix = Matrix4x4.TRS(Vector3.zero, Quaternion.identity,
            new Vector3(Screen.width / 1200.0f, Screen.height / 800.0f, 1.0f));
        GUI.Label(new Rect(10, 10, 800, 370), _logStr, new GUIStyle()
        {
            fontSize = Math.Max(10, fontSize)
        });
    }

    private void Update()
    {
        if (Input.GetKeyDown(KeyCode.Space))
        {
            Debug.Log(Time.time);
        }
    }
}